import config from '../config';
import { CanvasEnum, CellStateEnum } from '../enum';
import { Cell, IModel, ModelConstructor } from '../types';

export default abstract class CanvasAbstract {
  public boardMatrixs: Cell[][] = [];
  public models: IModel[] = [];
  abstract model(): ModelConstructor;

  constructor(
    protected name: CanvasEnum,
    protected app: HTMLDivElement = document.querySelector('#app')!,
    protected el: HTMLCanvasElement = document.createElement('canvas')!,
    public ctx = el.getContext('2d')!,
    public btns: HTMLDivElement = document.querySelector('#btns')!,
    public readonly cellWidth: number = config.cell.width,
    public readonly cellheight: number = config.cell.height,
    public readonly boardWidth: number = config.board.width,
    public readonly boardHeight: number = config.board.height
  ) {
    this.boardMatrixs = this.initMatrix();
    this.createCanvas();
  }

  protected createCanvas() {
    this.el.width = this.boardWidth;
    this.el.height = this.boardHeight;
    this.el.setAttribute('id', this.name);
    this.ctx.fillStyle = 'rgba(0, 0, 0, 0)';
    this.ctx.fillRect(0, 0, this.boardWidth, this.boardHeight);
    this.app.insertAdjacentElement('afterbegin', this.el);
  }

  private initMatrix(): Cell[][] {
    return Array<number>(Math.floor(this.boardWidth / this.cellheight))
      .fill(0)
      .map(() =>
        Array(Math.floor(this.boardWidth / this.cellWidth)).fill(
          CellStateEnum.death
        )
      );
  }

  public renderModels() {
    this.ctx.clearRect(0, 0, this.boardWidth, this.boardHeight);
    console.log(this.models);
    this.models.forEach(model => model.render());
  }
}
